#!/usr/bin/env python
# coding = UTF-8
import os.path
import re

from build_file import build_gn_file
import datetime

from config import cflag_black_list


def get_txt_datas(txt_path, save_file=None):
    time_now = datetime.datetime.now()
    date_time = "%s-%s-%s" % (time_now.year, time_now.month, time_now.day)
    built_target = dict()
    built_target["ohos_shared_library"] = dict()
    built_target["ohos_static_library"] = dict()
    built_target["ohos_executable"] = dict()
    part_name_list = txt_path.split('/')
    file_name = part_name_list[-1]
    file_name_list = file_name.split('.')
    part_name = file_name_list[0]
    with open(txt_path, encoding='utf-8') as file:
        check_content = file.read()
    with open(txt_path, encoding='utf-8') as file:
        content = file.readlines()
    __find_built_target(check_content, content, built_target, part_name)
    print('读取成功')
    build_gn_file(built_target, part_name)
    return built_target

def __find_built_target(check_content, content, built_target, part_name):
    if check_content.find(r'Linking') != -1:
        linking_helper(content, built_target, part_name)
    print(built_target)
    print('\n++++++++++++++++++++++++++++++++++++++\n')
    print(built_target["ohos_executable"])
    print('\n++++++++++++++++++++++++++++++++++++++\n')
    print(built_target["ohos_static_library"])

def linking_helper(content, built_target, part_name):
    last_counter = 0
    for i in range(len(content)):
        # print(last_counter)
        if content[i].find('Linking') != -1:
            if content[i].find('CXX static library') != -1 or content[i].find('C static library') != -1:
                path = '/home/ohos/cmake_gn/'+part_name
                linking_str = content[i].split(' ')[-1]
                name_str = linking_str.split('/')[-1].replace('\n', '')
                name = name_str[3:]
                cflags = list()
                cflags_cc = list()
                dir = list()
                source = list()
                deps = list()
                print('ohos_static_library:  ' + name)
                last_counter =__load_data_helper(content, last_counter, i, cflags, cflags_cc, dir, source)
                built_target["ohos_static_library"][name] = dict()
                built_target["ohos_static_library"][name]['configs'] = dict()
                built_target["ohos_static_library"][name]['configs']['cflags'] = cflags
                built_target["ohos_static_library"][name]['configs']['cflags_cc'] = cflags_cc
                built_target["ohos_static_library"][name]['include_dirs'] = dir
                built_target["ohos_static_library"][name]['sources'] = source
                built_target["ohos_static_library"][name]['deps'] = deps
                built_target["ohos_static_library"][name]['path'] = path
            elif content[i].find('shared library') != -1:
                # pattern_path = r'cd /root/test/.*/build(.*) &&.*'
                path = '/home/ohos/cmake_gn/' + part_name
                linking_str = content[i].split(' ')[-1]
                name_str = linking_str.split('/')[-1].replace('\n', '')
                name = name_str[3:]
                cflags = list()
                cflags_cc = list()
                dir = list()
                source = list()
                deps = list()
                print('shared_library:  ' + name)
                pattern_dep = r'lib(.*)'
                dep_str = re.search(pattern_dep, content[i+2]).group()
                print('dep_stt: '+dep_str)
                dep_list = dep_str.split(' ')
                print(dep_list)
                for dep_item in dep_list:
                    if dep_item.find('.so') != -1:
                        pattern_lib = r'.*lib(.*.so).*'
                        dep_so = re.match(pattern_lib, dep_item).group(1)
                        if dep_so != name and dep_so not in deps:
                            print(dep_so)
                            deps.append(dep_so)
                    elif dep_item.endswith('.a'):
                        pattern_a = r'.* lib(.*.a).*'
                        dep_lib = re.match(pattern_a, dep_item).group(1)
                        if dep_lib != name and dep_lib not in deps:
                            deps.append(dep_lib)
                last_counter =__load_data_helper(content, last_counter, i, cflags, cflags_cc, dir, source)
                built_target["ohos_shared_library"][name] = dict()
                built_target["ohos_shared_library"][name]['configs'] = dict()
                built_target["ohos_shared_library"][name]['configs']['cflags'] = cflags
                built_target["ohos_shared_library"][name]['configs']['cflags_cc'] = cflags_cc
                built_target["ohos_shared_library"][name]['include_dirs'] = dir
                built_target["ohos_shared_library"][name]['sources'] = source
                built_target["ohos_shared_library"][name]['deps'] = deps
                built_target["ohos_shared_library"][name]['path'] = path
            elif content[i].find('executable') != -1:
                path = '/home/ohos/cmake_gn/' + part_name
                linking_str = content[i].split(' ')[-1]
                name_str = linking_str.split('/')[-1]
                name = name_str.replace('\n', '')
                cflags = list()
                cflags_cc = list()
                dir = list()
                source = list()
                deps = list()
                print('CXX executable:  ' + name)
                pattern_dep = r'lib(.*)'
                dep_str = re.search(pattern_dep, content[i + 2]).group()
                dep_list = dep_str.split(' ')
                print(dep_list)
                for dep_item in dep_list:
                    # print(dep_item)
                    if dep_item.find('.so') != -1:
                        pattern_lib = r'.*lib(.*.so).*'
                        dep_so = re.match(pattern_lib, dep_item).group(1)
                        if dep_so != name and dep_so not in deps:
                            print(dep_so)
                            deps.append(dep_so)
                    elif dep_item.endswith('.a'):
                        pattern_a = r'.*lib(.*.a).*'
                        dep_lib = re.match(pattern_a, dep_item).group(1)
                        if dep_lib != name and dep_lib not in deps:
                            deps.append(dep_lib)
                # print(deps)
                last_counter =__load_data_helper(content, last_counter, i, cflags, cflags_cc, dir, source)
                built_target["ohos_executable"][name] = dict()
                built_target["ohos_executable"][name]['configs'] = dict()
                built_target["ohos_executable"][name]['configs']['cflags'] = cflags
                built_target["ohos_executable"][name]['configs']['cflags_cc'] = cflags_cc
                built_target["ohos_executable"][name]['include_dirs'] = dir
                built_target["ohos_executable"][name]['sources'] = source
                built_target["ohos_executable"][name]['deps'] = deps
                built_target["ohos_executable"][name]['path'] = path

def __load_data_helper(content, last_counter, i, cflags, cflags_cc, dir, source):
    pattern_dir = r'-I(/.*)'
    for n in range(last_counter, i):
        if (content[n].rstrip().endswith('.cpp.o') or content[n].rstrip().endswith('.cc.o') or content[n].rstrip().endswith('.cxx.o')) and content[n].find('] Building') != -1:
            str_list = content[n + 1].rstrip('\n').split(' ')
            print(str_list)
            for item in str_list:
                if item.startswith('-I'):
                    include_dir = re.match(pattern_dir, item).group(1)
                    if include_dir not in dir:
                        dir.append(include_dir)
                elif item.startswith('-') and item not in cflags_cc and item not in cflag_black_list:
                    cflags_cc.append(item)
                elif item.endswith('.cpp') or item.endswith('.cxx') or item.endswith('.cc') and item not in source:
                    source.append(item)
        elif content[n].find('] Building') != -1 and content[n].rstrip().endswith('.c.o'):
            str_list = content[n + 1].rstrip('\n').split(' ')
            print(str_list)
            for item in str_list:
                if item.startswith('-I'):
                    include_dir = re.match(pattern_dir, item).group(1)
                    if include_dir not in dir:
                        dir.append(include_dir)
                elif item.startswith('-') and item not in cflags and item not in cflag_black_list:
                    cflags.append(item)
                elif item.endswith('.c') and item not in source:
                    source.append(item)
    last_counter = i
    return last_counter

def no_linking_helper(content, built_target):
    return built_target

import sys

if __name__ == "__main__":
    txt_path = sys.argv[1]
    get_txt_datas(txt_path)